import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Input } from '@/components/ui/input';
import { useVocabulary } from '@/contexts/VocabularyContext';
import { Lock, Heart, Sparkles } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

export default function PetTab() {
  const { pets, userProgress, feedPet } = useVocabulary();
  const { toast } = useToast();
  const [feedAmount, setFeedAmount] = useState<{ [key: string]: number }>({});

  const handleFeed = (petId: string) => {
    const amount = feedAmount[petId] || 10;
    
    if (amount <= 0) {
      toast({
        title: '投喂失败',
        description: '请输入有效的经验值数量',
        variant: 'destructive',
      });
      return;
    }

    if (amount > userProgress.availableExperience) {
      toast({
        title: '经验值不足',
        description: `你只有 ${userProgress.availableExperience} 点可用经验值`,
        variant: 'destructive',
      });
      return;
    }

    feedPet(petId, amount);
    toast({
      title: '投喂成功！',
      description: `你的宠物获得了 ${amount} 点经验值`,
    });
    setFeedAmount({ ...feedAmount, [petId]: 10 });
  };

  const handleAmountChange = (petId: string, value: string) => {
    const amount = parseInt(value) || 0;
    setFeedAmount({ ...feedAmount, [petId]: amount });
  };

  return (
    <div className="space-y-6">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">我的宠物伙伴</h2>
        <p className="text-gray-600">通过学习单词获得经验值，投喂给宠物让它们成长</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {pets.map((pet) => (
          <Card
            key={pet.id}
            className={`relative overflow-hidden transition-all duration-300 ${
              pet.isUnlocked
                ? 'hover:shadow-xl hover:scale-105 border-2 border-purple-200'
                : 'opacity-60 bg-gray-50'
            }`}
          >
            {!pet.isUnlocked && (
              <div className="absolute inset-0 bg-gray-900/50 backdrop-blur-sm z-10 flex items-center justify-center">
                <div className="text-center text-white">
                  <Lock className="h-12 w-12 mx-auto mb-2" />
                  <p className="font-semibold">未解锁</p>
                  <p className="text-sm mt-1">{pet.description}</p>
                </div>
              </div>
            )}

            <CardHeader className="pb-4">
              <div className="flex items-center justify-between">
                <CardTitle className="text-xl">{pet.name}</CardTitle>
                <div className="flex items-center gap-1 bg-yellow-100 px-3 py-1 rounded-full">
                  <Sparkles className="h-4 w-4 text-yellow-600" />
                  <span className="text-sm font-bold text-yellow-700">Lv.{pet.level}</span>
                </div>
              </div>
              <CardDescription>{pet.description}</CardDescription>
            </CardHeader>

            <CardContent className="space-y-4">
              {/* 宠物图片 */}
              <div className="relative aspect-square rounded-lg overflow-hidden bg-gradient-to-br from-purple-100 to-pink-100">
                <img
                  src={pet.image}
                  alt={pet.name}
                  className="w-full h-full object-cover"
                />
              </div>

              {pet.isUnlocked && (
                <>
                  {/* 经验值进度条 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-gray-600 flex items-center gap-1">
                        <Heart className="h-4 w-4 text-red-500" />
                        经验值
                      </span>
                      <span className="font-semibold text-purple-600">
                        {pet.experience} / {pet.maxExperience}
                      </span>
                    </div>
                    <Progress
                      value={(pet.experience / pet.maxExperience) * 100}
                      className="h-3"
                    />
                  </div>

                  {/* 投喂控制 */}
                  <div className="space-y-2 pt-2 border-t">
                    <label className="text-sm font-medium text-gray-700">投喂经验值</label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        min="1"
                        max={userProgress.availableExperience}
                        value={feedAmount[pet.id] || 10}
                        onChange={(e) => handleAmountChange(pet.id, e.target.value)}
                        className="flex-1"
                      />
                      <Button
                        onClick={() => handleFeed(pet.id)}
                        disabled={userProgress.availableExperience === 0}
                        className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600"
                      >
                        投喂
                      </Button>
                    </div>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 提示信息 */}
      <Card className="bg-gradient-to-r from-blue-50 to-purple-50 border-blue-200">
        <CardContent className="pt-6">
          <div className="flex items-start gap-3">
            <div className="text-3xl">💡</div>
            <div>
              <h3 className="font-semibold text-gray-900 mb-1">如何获得经验值？</h3>
              <ul className="text-sm text-gray-600 space-y-1">
                <li>• 完成单词配对游戏：获得 10 点经验值</li>
                <li>• 拼写练习：每答对一个单词获得 2 点经验值</li>
                <li>• 快速测验：根据得分获得经验值（得分÷10）</li>
                <li>• 解锁新宠物：学习 50 个单词解锁小狗狗，100 个单词解锁小兔子</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
